package sdu.icat.pj.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sdu.icat.pj.base.AbstractController;
import sdu.icat.pj.base.ResponseMap;
import sdu.icat.pj.service.SysUserService;
import sdu.icat.pj.util.JudgeUtil;
import sdu.icat.pj.util.MD5Util;
import sdu.icat.pj.util.WebUtil;
import sdu.icat.sys.smodel.SysUser;

@RestController
@Api(value="userManager",tags={"userManager"})
@RequestMapping("/sysusr")
public class SysUserController implements AbstractController {

    @Autowired private SysUserService sysUserService;
    
    @PostMapping("update")
    @ApiOperation(value="新增/修改用户信息")
    @RequiresPermissions("sys.base.user.update")
    public ResponseMap update(ModelMap modelMap,@RequestBody SysUser param) {
	ResponseMap result = new ResponseMap();
	String account = param.getAccount();
	String password = param.getPassword();
	Assert.notNull(account,"ACCOUNT");
	Assert.isTrue(JudgeUtil.legalizedAccountLength(account, 3, 10), "ACCOUNT");
	if(param.getId() != null) {
	    if(param.getEnable() == null) {
		param.setEnable(0);
	    }
	    SysUser user = sysUserService.queryById(param.getId());
	    Assert.notNull(user, "USER");
	    if(StringUtils.isNotBlank(password)) {
		if(!user.getPassword().equals(password)) {
		    param.setPassword(MD5Util.getMD5Password(account, password));
		}
	    }
	    result.put("code", 1);
	    result.put("codeMsg", "更新用户");
	} else if(StringUtils.isNoneBlank(password)) {
	    param.setPassword(MD5Util.getMD5Password(account, password));
	    result.put("code", 2);
	    result.put("codeMsg", "新增用户");
	}
	result.put("account", param.getAccount());
	sysUserService.saveOrUpdate(param);
	return result;
    }
    
    @ApiOperation(value="查询用户")
    @RequiresPermissions("sys.base.user.read")
    @PutMapping(value="/read/list")
    public ResponseMap query(String account) {
	ResponseMap map = new ResponseMap();
	SysUser user = sysUserService.queryOne(account);
	map.setStatus(1);
	map.putMsg("success");
	map.setAttribute("obj", user);
	return map;
    }
    
    @ApiOperation(value="用户详细信息")
    @RequiresPermissions("sys.base.user.read")
    public ResponseMap get(@RequestBody SysUser param) {
	ResponseMap map = new ResponseMap();
	map.setAttribute("obj", param);
	return map;
    }
    
    @ApiOperation(value="删除用户")
    @RequiresPermissions("sys.base.user.delete")
    @DeleteMapping
    public ResponseMap delete(ModelMap modelMap,@RequestBody SysUser param) {
	ResponseMap map = new ResponseMap();
	if(sysUserService.delete(param)!=null) {
	    map.setStatus(1);
	    map.putMsg("delete success");
	} else {
	    map.setStatus(0);
	    map.putMsg("some errors during delete action");
	}
	return map;
    }
    
    @ApiOperation(value="用户查询")
    @RequiresPermissions("sys.base.user.read")
    @PutMapping(value="/sys/list")
    public ResponseMap query(ModelMap modelMap,@RequestBody Map<String,Object> param) {
	ResponseMap map = new ResponseMap();
	List<SysUser> users = sysUserService.queryByMap(param);
	map.setAttribute("data", users);
	map.setStatus(1);
	map.putMsg("success query");
	return map;
    }
    
    @ApiOperation(value="当前用户信息")
    @GetMapping(value="/read/promission")
    public ResponseMap promission() {
	ResponseMap map = new ResponseMap();
	Long id = WebUtil.getCurrentUser();
	SysUser user = sysUserService.queryById(id);
	map.setStatus(1);
	map.putMsg("OK");
	map.setData(user);
	return map;
    }
    
    @ApiOperation(value="修改密码")
    @PostMapping(value="update/password")
    public ResponseMap updatePassword(ModelMap modelMap,@RequestBody SysUser param) {
	ResponseMap map = new ResponseMap();
	String newpassword = param.getPassword();
	Assert.notNull(newpassword, "NEWPASSWORD");
	Long id = param.getId();
	Assert.notNull(id,"No Object!");
	SysUser user = sysUserService.queryById(id);
	String encryptPassword = MD5Util.getMD5Password(user.getAccount(), newpassword);
	if(!user.getPassword().endsWith(encryptPassword)) {
	    throw new UnauthorizedException("原密码错误.");
	}
	user.setPassword(encryptPassword);
	sysUserService.saveOrUpdate(user);
	map.setStatus(1);
	map.putMsg("密码修改成功");
	return map;
    }
    
//    @ApiOperation(value = "修改用户头像")
//    @PostMapping(value = "/upload/avatar")
//    public Object updateAvatar(HttpServletRequest request, ModelMap modelMap) {
//        List<String> fileNames = UploadUtil.uploadImageData(request);
//        if (fileNames.size() > 0) {
//            SysUser param = new SysUser();
//            param.setId(WebUtil.getCurrentUser());
//            for (int i = 0; i < fileNames.size(); i++) {
//                String filePath = UploadUtil.getUploadDir(request) + fileNames.get(i);
//                String avatar = UploadUtil.remove2DFS("sysUser", "U" + param.getId(), filePath).getRemotePath();
//                param.setAvatar(avatar);
//            }
//            modelMap.put("data", param);
//            return super.update(modelMap, param);
//        } else {
//            setModelMap(modelMap, HttpCode.BAD_REQUEST);
//            modelMap.put("msg", "请选择要上传的文件！");
//            return modelMap;
//        }
//    }
    
}
